package info.scholtus.open.ui;

import static info.scholtus.open.util.LogUtils.LOGI;
import static info.scholtus.open.util.LogUtils.makeLogTag;
import info.scholtus.open.R;
import info.scholtus.open.provider.Contract.Categories;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.SimpleCursorAdapter;
import android.view.View;
import android.widget.ListView;

import com.actionbarsherlock.app.SherlockListFragment;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;

public class CategoriesFragment extends SherlockListFragment implements LoaderManager.LoaderCallbacks<Cursor> {
	
    private static final String TAG = makeLogTag(CategoriesFragment.class);
    private static final int INSERT_CATEGORY_REQUEST = 0;

	// This is the Adapter being used to display the list's data.
	SimpleCursorAdapter mAdapter;

    @Override public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        
        // Give some text to display if there is no data. 
        // In a real application this would come from a resource.
        setEmptyText("Nothing to show");

        // We have a menu item to show in action bar.
        setHasOptionsMenu(true);
        
        // Create an empty adapter we will use to display the loaded data.
        mAdapter = new SimpleCursorAdapter(getActivity(),
                android.R.layout.simple_list_item_1, null,
                new String[] { Categories.CATEGORY_NAME },
                new int[] { android.R.id.text1 }, 0);
        setListAdapter(mAdapter);
        
        // Start or re-connect a LoaderManager instance.
        getActivity().getSupportLoaderManager().initLoader(0, null, this);
    }
    
    @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        // Place an action bar item for searching.
        MenuItem item = menu.add(R.string.menu_category_add);
        item.setIcon(android.R.drawable.ic_menu_add);
        item.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
    }
    
    @Override public boolean onOptionsItemSelected(MenuItem item) {
    	
    	Intent intent = new Intent(getActivity(),CategoryAddActivity.class);
    	intent.setData(Categories.CONTENT_URI);
    	
    	startActivityForResult(intent, INSERT_CATEGORY_REQUEST);
    	
    	return true;
    	// return super.onOptionsItemSelected(item);
    }
    
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
    	
    	LOGI(TAG,"requestCode: " + requestCode + " - " + "resultCode: " + resultCode);
    	
    	// I'm receiving everything blank :-/ So lets just update always
    	
    	//if (requestCode == INSERT_CATEGORY_REQUEST) {
    		//if (!data.getData().equals(Categories.CONTENT_URI)) {
    			getActivity().getSupportLoaderManager().initLoader(0, null, this);
				getActivity().getSupportLoaderManager().getLoader(0).reset();
    		//}
    	//}
    }
	
	@Override public Loader<Cursor> onCreateLoader(int id, Bundle args) {
		
		final String[] projection = new String[] {
				BaseColumns._ID,
				Categories.CATEGORY_ID,
				Categories.CATEGORY_NAME
		};
		
		return new CursorLoader(getActivity(), Categories.CONTENT_URI, 
				projection, null, null, null);
	}

	@Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
		// Swap the new cursor in.  (The framework will take care of closing the
	    // old cursor once we return.)
	    mAdapter.swapCursor(data);
	}

	@Override public void onLoaderReset(Loader<Cursor> arg0) {
		// This is called when the last Cursor provided to onLoadFinished()
	    // above is about to be closed.  We need to make sure we are no
	    // longer using it.
		
		// This breaks :-/
	    //mAdapter.swapCursor(null);
	}
	
	@Override public void onListItemClick(ListView l, View v, int position, long id) {
        // Insert desired behavior here.
		LOGI(TAG, "Item clicked: " + id);
		
		final Uri uri = Categories.buildCategoryUri(
				((Cursor) l.getItemAtPosition(position)).getString(1)); 

		LOGI(TAG, "Uri: " + uri.toString());
		
		Intent intent = new Intent(getActivity(),VendorsListActivity.class);
    	intent.setData(uri);
    	
		startActivity(intent);
    }
}
